package com.ft.FileTest.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ft.FileTest.service.FileService;
@Controller
@RequestMapping("/file")
public class FileController {
	@Autowired
	private FileService fileService;
	
	@RequestMapping("/upload")
	@ResponseBody
	public void uploadFile(@RequestParam("file")MultipartFile multipartFile,HttpServletResponse response){
		try{
//			String result = fileService.uploadFile(multipartFile);
//			result = "10.0.0.115:8080/" + result;
			String result = "10.0.0.115:8080/M00/00/00/CgAAc1cLRLuAAqr1AAB_iXpoIzg622.png";
//			String responseText = "<script language='javascript'>window.parent.handle(" + result + ")</script>";
			String responseText = "<script>window.parent.handle('"+result+"')</script>";
//			System.out.println("result = "+responseText);
//			return responseText;
			response.getWriter().println(responseText);
		}catch(Exception e){
			System.out.println(e.getMessage());
//			return "failure";
		}
	}
	
	@RequestMapping(value = "download")
	public void downLoadFile(@RequestParam("fileUrl") String fileUrl, HttpServletResponse response) {
		// Map<String, Object> map = JsonUtil.json2map(json);
		// String fileid = (String) map.get("fileurl");
//		if (StringUtils.isEmpty(fileurl)) {
//			return;
//		}

		int filenameindex = fileUrl.indexOf("?filename=");
		String filename = fileUrl.substring(filenameindex + 1);

		byte[] filebyte = fileService.downloadFile(fileUrl);

		try {
			// response.setContentType("image/jpeg");
			// response.setHeader("Pragma", "no-cache");
			// response.setHeader("Cache-Control", "no-cache");
			// response.setDateHeader("Expires", 0);
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename=" + "dddsss.txt");

			response.getOutputStream().write(filebyte);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@RequestMapping("/remove")
	public String removeFile(){
		return null;
	}
}
